package pre.liuxl.blog.repository;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import pre.liuxl.blog.entity.User;

import java.util.List;

/**
 * Created by liuxuanlong on 2018/6/16.
 */
@Repository

public class UserRepository {

    @Autowired
    HibernateTemplate hibernateTemplate;
    @Autowired
    SessionFactory sessionFactory;

    /**
     * 此方法事务不能回滚
     */
    @Transactional(rollbackFor = Exception.class)
    public void addUser() {

        User user = hibernateTemplate.get(User.class, 1);

        user.setUserName("bbba");
        hibernateTemplate.update(user);

        User user1 = new User();
        user1.setPassword("aa");
        user1.setUserName("aaa");
        hibernateTemplate.save(user1);

        throw new RuntimeException();
    }


    public User findByUserNameAndPassword(String userName, String password) {
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        List<User> userList = hibernateTemplate.findByExample(user);
        if (1 == userList.size()) {
            return userList.get(0);
        } else {
            return null;
        }
    }

    public User findByUserId(Integer userId) {

        return hibernateTemplate.get(User.class, userId);
    }


}
